package com.bw.kf.playvideo

// 添加Room数据库相关导入
import android.app.PictureInPictureParams
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.graphics.Color
import android.graphics.Rect
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.util.Rational
import android.view.View
import android.view.ViewGroup
import android.widget.SeekBar
import androidx.activity.viewModels
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.example.common.mvi.BaseActivity
import com.example.common.mvi.SingleEvent
import com.example.common.room.VideoDatabase
import com.example.common.room.VideoFavorite
import com.example.common.room.VideoRepository
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.MediaItem
import com.google.android.exoplayer2.PlaybackException
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.source.ProgressiveMediaSource
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory
import com.google.android.exoplayer2.util.Util
import com.google.gson.Gson
import com.umeng.socialize.ShareAction
import com.umeng.socialize.UMAuthListener
import com.umeng.socialize.UMShareListener
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMVideo
import kotlinx.coroutines.launch
import master.flame.danmaku.danmaku.model.BaseDanmaku
import master.flame.danmaku.danmaku.model.IDanmakus
import master.flame.danmaku.danmaku.model.android.DanmakuContext
import master.flame.danmaku.danmaku.model.android.Danmakus
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser
import master.flame.danmaku.ui.widget.DanmakuView
import master.flame.danmaku.controller.IDanmakuView
import master.flame.danmaku.controller.DrawHandler
import master.flame.danmaku.danmaku.model.IDisplayer
import org.jash.playvideo.R
import org.jash.playvideo.databinding.ActivityPlayVideoBinding
import com.bw.kf.playvideo.UserManager
import com.bw.kf.playvideo.CommentsDialog
import com.bw.kf.playvideo.HomeData


@Route(path = "/playvideo/PlayVideoActivity")
class PlayVideoActivity : BaseActivity<ActivityPlayVideoBinding, PlayVideoViewModel, PlayVideoIntent, PlayVideoViewState>() {

    private var exoPlayer: ExoPlayer? = null
    private var progressUpdateHandler: Handler? = null
    private var progressUpdateRunnable: Runnable? = null
    private var isFullscreen = false
    private var savedPlaybackPosition: Long = 0
    private var LookVider: Int = 0
    private lateinit var da:String
    private lateinit var bt:String
    private lateinit var ms:String
    private lateinit var tp:String
    private var savedPlayWhenReady: Boolean = true
    lateinit var danmakuContext: DanmakuContext

    // 添加Room数据库相关变量
    private lateinit var videoRepository: VideoRepository
    private var currentVideoId: Int = 0
    private var videoId: String = ""

    @Autowired
    @JvmField
    var videoDataJson: String = ""

    override val viewModel: PlayVideoViewModel by viewModels()
    private var videoData: HomeData? = null

    override fun getLayoutId(): Int = R.layout.activity_play_video

    override fun onCreate(savedInstanceState: Bundle?) {
        requestPermissions(
            arrayOf(
                "android.permission.VIBRATE",
                "android.permission.RECORD_AUDIO" ,
                "android.permission.CAMERA",
                "android.permission.ACCESS_NETWORK_STATE",
                "android.permission.WRITE_EXTERNAL_STORAGE" ,
                "android.permission.ACCESS_FINE_LOCATION",
                "android.permission.GET_TASKS" ,
                "android.permission.ACCESS_WIFI_STATE" ,
                "android.permission.CHANGE_WIFI_STATE" ,
                "android.permission.WAKE_LOCK",
                "android.permission.MODIFY_AUDIO_SETTINGS",
                "android.permission.READ_PHONE_STATE",
                "android.permission.RECEIVE_BOOT_COMPLETED",
                "android.permission.FOREGROUND_SERVICE",
                "android.permission.ACCESS_COARSE_LOCATION"
            ),100
        )
        super.onCreate(savedInstanceState)
        
        // 强制设置竖屏模式启动，确保不会自动进入全屏
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        isFullscreen = false
        
        // 优化视频播放性能
        window.setFlags(
            android.view.WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
            android.view.WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED
        )
        
        ARouter.getInstance().inject(this)
        danmuInit()
        // 初始化Room数据库
        initDatabase()
        parseVideoData()
        setupCommentSystem() // 确保调用这个方法
        
        ViewCompat.setOnApplyWindowInsetsListener(binding.main) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        binding.send.setOnClickListener {

            if (binding.dm.text.isEmpty()) {
                ToastUtils.showShort("请输入弹幕内容")
                return@setOnClickListener
            }

            // 创建弹幕对象
            val danmaku = danmakuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL)
            
            // 设置弹幕内容和样式
            danmaku.text = binding.dm.text.toString()
            danmaku.textSize = 50f
            // 设置弹幕出现的时间，单位：毫秒，这里设置为当前播放器的时间
            danmaku.time = exoPlayer?.currentPosition ?: System.currentTimeMillis()
            danmaku.textColor = Color.RED
            danmaku.borderColor = Color.YELLOW
            danmaku.underlineColor = Color.GREEN
            danmaku.textShadowColor = Color.DKGRAY

            // 添加弹幕到弹幕视图
            binding.dan.addDanmaku(danmaku)
            
            // 确保弹幕视图正在运行
            if (!binding.dan.isShown) {
                binding.dan.show()
            }
            if (!binding.dan.isPrepared) {
                binding.dan.prepare(object : BaseDanmakuParser() {
                    override fun parse(): IDanmakus = Danmakus()
                }, danmakuContext)
            }
            if (!binding.dan.isDrawingCacheEnabled) {
                binding.dan.enableDanmakuDrawingCache(true)
            }
            if (binding.dan.isPaused) {
                binding.dan.resume()
            }
            
            // 清空输入框并显示成功提示
            binding.dm.text = null
            ToastUtils.showShort("发送成功")
        }
        binding.btnShare.setOnClickListener {
            val video: UMVideo = UMVideo(da)
            video.title = bt //视频的标题
            val image: UMImage = UMImage(
                this@PlayVideoActivity,
                "https://img.shetu66.com/2023/04/25/1682391088794617.png"
            ) //网络图片
            video.setThumb(image) //视频的缩略图
            video.description = ms //视频的描述


            ShareAction(this).withText("hello")
                .setDisplayList(SHARE_MEDIA.SINA, SHARE_MEDIA.QQ, SHARE_MEDIA.WEIXIN)
                .withMedia(video)
                .setCallback(object : UMShareListener {
                    override fun onStart(p0: SHARE_MEDIA?) {
                    }

                    override fun onResult(p0: SHARE_MEDIA?) {
                    }

                    override fun onError(p0: SHARE_MEDIA?, p1: Throwable?) {
                        ToastUtils.showShort("${p1?.message}")
                    }

                    override fun onCancel(p0: SHARE_MEDIA?) {
                        ToastUtils.showShort("取消分享")
                    }
                })
                .open()

        }


    }

    // 弹幕初始化方法
    private fun danmuInit() {
        // 简化的弹幕初始化逻辑
        danmakuContext = DanmakuContext.create()
        
        // 设置弹幕样式
        val maxLinesPair = HashMap<Int, Int>()
        maxLinesPair[BaseDanmaku.TYPE_SCROLL_RL] = 5 // 滚动弹幕最大显示5行
        
        // 设置是否禁止重叠
        val overlappingEnablePair = HashMap<Int, Boolean>()
        overlappingEnablePair[BaseDanmaku.TYPE_SCROLL_RL] = true
        overlappingEnablePair[BaseDanmaku.TYPE_FIX_TOP] = true
        
        // 简化弹幕样式设置
        danmakuContext.setDuplicateMergingEnabled(false)
            .setScrollSpeedFactor(1.2f)
            .setScaleTextSize(1.2f)
            .setMaximumLines(maxLinesPair)
            .preventOverlapping(overlappingEnablePair)
            .setDanmakuTransparency(0.8f)
        
        // 创建简化的弹幕解析器
        val parser = object : BaseDanmakuParser() {
            override fun parse(): IDanmakus {
                return Danmakus()
            }
        }
        
        // 直接准备弹幕控件，不使用复杂回调
        binding.dan.prepare(parser, danmakuContext)
        binding.dan.enableDanmakuDrawingCache(true)
        binding.dan.show()
    }

    // 初始化数据库
    private fun initDatabase() {
        val database = VideoDatabase.getDatabase(this)
        videoRepository = VideoRepository(database.videoFavoriteDao())
    }

    // 初始化评论系统
    private fun setupCommentSystem() {
        // 初始化UserManager
        UserManager.init(this)

        // 设置评论按钮点击事件
        binding.ivComment.setOnClickListener {
            showCommentsDialog()
        }
    }

    private fun showCommentsDialog() {
        val commentsDialog = CommentsDialog(
            context = this,
            videoId = videoId.toIntOrNull() ?: 0, // 将String转换为Int
            videoRepository = videoRepository,
            onCommentAdded = { comment ->
                // 不再处理新评论添加，避免重复添加
                // viewModel.addNewComment(comment)
            }
        )
        commentsDialog.show()
    }

    // 全屏切换方法
    private fun toggleFullscreen() {
        if (isFullscreen) {
            // 退出全屏
            isFullscreen = false
            binding.btnFullscreen.setImageResource(R.drawable.baseline_fullscreen_24)
            
            // 调整播放器布局参数 - 设置固定高度
            val params = binding.playerView.layoutParams
            params.height = resources.getDimensionPixelSize(R.dimen.video_player_height) // 使用资源中定义的高度
            binding.playerView.layoutParams = params
            
            // 显示底部内容
            binding.scrollView.visibility = View.VISIBLE
            
            // 显示弹幕输入框和发送按钮
            binding.dm.visibility = View.VISIBLE
            binding.send.visibility = View.VISIBLE
        } else {
            // 进入全屏 - 保持竖屏但占满整个屏幕
            isFullscreen = true
            binding.btnFullscreen.setImageResource(R.drawable.baseline_fullscreen_exit_24)
            // 调整播放器布局参数 - 全屏时占满整个屏幕
            val params = binding.playerView.layoutParams
            params.height = ViewGroup.LayoutParams.MATCH_PARENT
            binding.playerView.layoutParams = params
            // 隐藏底部内容
            binding.scrollView.visibility = View.GONE
            // 隐藏弹幕输入框和发送按钮
            binding.dm.visibility = View.GONE
            binding.send.visibility = View.GONE
        }
    }

    // 存储播放次数的变量
    private var playCount = 0
    
    private fun parseVideoData() {
        try {
            if (videoDataJson.isNotEmpty()) {
                println("解析视频数据: $videoDataJson")
                videoData = Gson().fromJson(videoDataJson, HomeData::class.java)
                videoData?.let { data ->
                    println("视频数据解析成功: title=\${data.title}, videopath=\${data.videopath}, avatar_url=\${data.avatar_url}")
                    currentVideoId = data.id
                    videoId = data.id.toString()
                    viewModel.setVideoData(data)
                    
                    // 播放次数加1
                    playCount = SPUtils.getInstance().getInt("play_count_" + data.id, 0) + 1
                    SPUtils.getInstance().put("play_count_" + data.id, playCount)
                    
                    // 更新播放次数和时间显示
                    updatePlayCountAndTime()

                    // 将视频数据添加到数据库（如果不存在）
                    addVideoToDatabase(data)

                    // 加载点赞收藏状态
                    loadLikeAndFavoriteStatus()

                    // 设置视频播放
                    setupVideoPlayer(data.videopath)
                    da = data.videopath
                    bt = data.title
                    ms = data.description
                    tp = data.image_url
                    // 加载头像
                    loadAvatar(data.avatar_url)
                }
            } else {
                println("视频数据JSON为空")
            }
        } catch (e: Exception) {
            e.printStackTrace()
            println("解析视频数据失败: \${e.message}")
        }
    }

    // 将视频数据添加到数据库
    private fun addVideoToDatabase(data: HomeData) {
        lifecycleScope.launch {
            try {
                val videoFavorite = VideoFavorite(
                    id = data.id,
                    avatar_url = data.avatar_url,
                    name = data.name,
                    title = data.title,
                    videopath = data.videopath
                )
                videoRepository.addVideoIfNotExists(videoFavorite)
            } catch (e: Exception) {
                e.printStackTrace()
                println("添加视频到数据库失败: \${e.message}")
            }
        }
    }

    // 加载点赞收藏状态
    // ... existing code ...
    // 加载点赞收藏状态
    private fun loadLikeAndFavoriteStatus() {
        // 使用lifecycleScope启动协程，确保在Activity生命周期内执行
        lifecycleScope.launch {
            try {
                val isLiked = videoRepository.isVideoLiked(currentVideoId)
                val isFavorited = videoRepository.isVideoFavorited(currentVideoId)

                // 更新UI
                updateLikeIcon(isLiked)
                updateFavoriteIcon(isFavorited)

                // 更新ViewModel状态
                if (isLiked) sendIntent(PlayVideoIntent.ToggleLike)
                if (isFavorited) sendIntent(PlayVideoIntent.ToggleCollect)

            } catch (e: Exception) {
                e.printStackTrace()
                println("加载点赞收藏状态失败: \${e.message}")
            }
        }

    }
// ... existing code ...


    // 更新点赞图标
    private fun updateLikeIcon(isLiked: Boolean) {
        if (isLiked) {
            binding.ivLike.setImageResource(R.drawable.ic_like_filled)
            binding.ivLike.setColorFilter(ContextCompat.getColor(this, R.color.gray_dark))
        } else {
            binding.ivLike.setImageResource(R.drawable.ic_like_outline)
            binding.ivLike.setColorFilter(ContextCompat.getColor(this, R.color.gray_light))
        }
    }

    // 更新收藏图标
    private fun updateFavoriteIcon(isFavorited: Boolean) {
        if (isFavorited) {
            binding.ivFavorite.setImageResource(R.drawable.ic_favorite_filled)
            binding.ivFavorite.setColorFilter(ContextCompat.getColor(this, R.color.gray_dark))
        } else {
            binding.ivFavorite.setImageResource(R.drawable.ic_favorite_outline)
            binding.ivFavorite.setColorFilter(ContextCompat.getColor(this, R.color.gray_light))
        }
    }
    
    // 更新播放次数和时间显示
    private fun updatePlayCountAndTime() {
        // 更新播放次数
        binding.tvPlayCount.text = "${playCount}次观看"
        
        // 获取当前系统时间并格式化
        val currentTime = java.text.SimpleDateFormat("yyyy-MM-dd HH:mm", java.util.Locale.getDefault())
            .format(java.util.Date())
        
        // 更新时间显示
        binding.tvUploadTime.text = currentTime
    }

    private fun setupVideoPlayer(videoPath: String) {
        try {
            // 初始化ExoPlayer，添加性能优化配置
             val loadControl = com.google.android.exoplayer2.DefaultLoadControl.Builder()
                 .setBufferDurationsMs(
                     com.google.android.exoplayer2.DefaultLoadControl.DEFAULT_MIN_BUFFER_MS,
                     com.google.android.exoplayer2.DefaultLoadControl.DEFAULT_MAX_BUFFER_MS,
                     com.google.android.exoplayer2.DefaultLoadControl.DEFAULT_BUFFER_FOR_PLAYBACK_MS / 2, // 减少播放前缓冲时间
                     com.google.android.exoplayer2.DefaultLoadControl.DEFAULT_BUFFER_FOR_PLAYBACK_AFTER_REBUFFER_MS / 2 // 减少重新缓冲时间
                 )
                 .setPrioritizeTimeOverSizeThresholds(true)
                 .build()
                
            exoPlayer = ExoPlayer.Builder(this)
                .setLoadControl(loadControl)
                .build()
                
            binding.playerView.player = exoPlayer
            
            // 设置播放器视图优化
             binding.playerView.setShutterBackgroundColor(Color.BLACK)
             binding.playerView.keepScreenOn = true
             
             // 设置视频缩放模式 - 使用FIT而不是FILL以避免全屏效果
             binding.playerView.resizeMode = com.google.android.exoplayer2.ui.AspectRatioFrameLayout.RESIZE_MODE_FIT

            // 创建数据源工厂（支持缓存）
            val dataSourceFactory = DefaultDataSourceFactory(
                this,
                Util.getUserAgent(this, "IVideo")
            )

            // 创建媒体源
            val mediaSource = ProgressiveMediaSource.Factory(dataSourceFactory)
                .createMediaSource(MediaItem.fromUri(videoPath))

            // 设置媒体源
            exoPlayer?.setMediaSource(mediaSource)

            // 准备播放器
            exoPlayer?.prepare()

            // 设置播放器监听器
            exoPlayer?.addListener(object : Player.Listener {
                override fun onPlaybackStateChanged(playbackState: Int) {
                    when (playbackState) {
                        Player.STATE_READY -> {
                            // 视频准备完成
                            val duration = exoPlayer?.duration ?: 0L
                            viewModel.updateDuration(duration)
                            // 自动播放
                            exoPlayer?.play()
                            sendIntent(PlayVideoIntent.PlayVideo)
                            startProgressUpdate()
                            // 确保弹幕控件也开始显示
                            if (binding.dan.isPaused) {
                                binding.dan.resume()
                            } else if (!binding.dan.isShown) {
                                binding.dan.show()
                            }
                        }

                        Player.STATE_BUFFERING -> {
                            // 缓冲中
                            sendIntent(PlayVideoIntent.PauseVideo)
                            // 暂停弹幕
                            if (!binding.dan.isPaused) {
                                binding.dan.pause()
                            }
                        }

                        Player.STATE_ENDED -> {
                            // 播放结束
                            stopProgressUpdate()
                            sendIntent(PlayVideoIntent.PauseVideo)
                            // 暂停弹幕
                            if (!binding.dan.isPaused) {
                                binding.dan.pause()
                            }
                        }
                    }
                }

                override fun onPlayerError(error: PlaybackException) {
                    println("ExoPlayer错误: ${error.message}")
                    stopProgressUpdate()
                }
            })

        } catch (e: Exception) {
            e.printStackTrace()
            println("设置ExoPlayer失败: ${e.message}")
        }
    }

    // 开始进度更新
    private fun startProgressUpdate() {
        if (progressUpdateHandler == null) {
            progressUpdateHandler = Handler(Looper.getMainLooper())
        }

        progressUpdateRunnable = object : Runnable {
            override fun run() {
                exoPlayer?.let { player ->
                    if (player.isPlaying) {
                        val currentPosition = player.currentPosition
                        sendIntent(PlayVideoIntent.SeekTo(currentPosition))
                    }
                }
                progressUpdateHandler?.postDelayed(this, 500) // 每0.5秒更新一次，更流畅
            }
        }

        progressUpdateRunnable?.let {
            progressUpdateHandler?.post(it)
        }
    }

    // 停止进度更新
    private fun stopProgressUpdate() {
        progressUpdateRunnable?.let {
            progressUpdateHandler?.removeCallbacks(it)
        }
    }

    private fun loadAvatar(avatarUrl: String) {
        try {
            Glide.with(this)
                .load(avatarUrl)
                .placeholder(R.drawable.ic_launcher_background)
                .error(R.drawable.ic_launcher_background)
                .into(binding.ivAuthorAvatar)
        } catch (e: Exception) {
            e.printStackTrace()
            println("加载头像失败: \${e.message}")
            // 设置默认头像
            binding.ivAuthorAvatar.setImageResource(R.drawable.ic_launcher_background)
        }
    }

    override fun setupViews() {
        // 设置返回按钮
        binding.btnBack.setOnClickListener {
            finish()
        }

        // 设置播放/暂停按钮
        binding.btnPlayPause.setOnClickListener {
            exoPlayer?.let { player ->
                if (player.isPlaying) {
                    player.pause()
                    stopProgressUpdate()
                    sendIntent(PlayVideoIntent.PauseVideo)
                    // 暂停弹幕
                    if (binding.dan.isPrepared && !binding.dan.isPaused) {
                        binding.dan.pause()
                    }
                } else {
                    player.play()
                    startProgressUpdate()
                    sendIntent(PlayVideoIntent.PlayVideo)
                    // 恢复弹幕
                    if (binding.dan.isPrepared && binding.dan.isPaused) {
                        binding.dan.resume()
                    }
                }
            }
        }

        // 添加全屏按钮点击事件
        binding.btnFullscreen.setOnClickListener {
            toggleFullscreen()
        }

        // 设置进度条拖拽监听器
        binding.seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    exoPlayer?.seekTo(progress.toLong())
                    sendIntent(PlayVideoIntent.SeekTo(progress.toLong()))
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                stopProgressUpdate()
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                exoPlayer?.let { player ->
                    if (player.isPlaying) {
                        startProgressUpdate()
                    }
                }
            }
        })

        // 设置点赞按钮 - 集成数据库操作
        binding.ivLike.setOnClickListener {
            lifecycleScope.launch {
                try {
                    val newLikeStatus = videoRepository.toggleLike(currentVideoId)
                    updateLikeIcon(newLikeStatus)
                    sendIntent(PlayVideoIntent.ToggleLike)

                    // 显示提示
                    val message = if (newLikeStatus) "点赞成功" else "取消点赞"
                    ToastUtils.showShort(message)
                } catch (e: Exception) {
                    e.printStackTrace()
                    println("点赞操作失败: \${e.message}")
                }
            }
        }

        // 设置收藏按钮 - 集成数据库操作
        binding.ivFavorite.setOnClickListener {
            lifecycleScope.launch {
                try {
                    val newFavoriteStatus = videoRepository.toggleFavorite(currentVideoId)
                    updateFavoriteIcon(newFavoriteStatus)
                    sendIntent(PlayVideoIntent.ToggleCollect)

                    // 显示提示
                    val message = if (newFavoriteStatus) "收藏成功" else "取消收藏"
                    ToastUtils.showShort(message)
                } catch (e: Exception) {
                    e.printStackTrace()
                    println("收藏操作失败: \${e.message}")
                }
            }
        }
    }


    override fun renderViewState(state: PlayVideoViewState) {
        // 处理评论加载状态
        if (state.isCommentsLoading) {
            // 显示加载状态
                            binding.progressBar.visibility = View.VISIBLE
        } else {
            binding.progressBar.visibility = View.GONE
        }
        
        // 更新评论列表
        state.comments.let { comments ->
            // 如果有评论适配器，更新数据
            // commentsAdapter.submitList(comments)
        }
     }
     
     override fun handleSingleEvent(event: SingleEvent) {
        when (event) {
            is SingleEvent.ShowToast -> {
                ToastUtils.showShort(event.message)
            }
            is SingleEvent.ShowError -> {
                ToastUtils.showShort(event.error)
            }
            is SingleEvent.Navigate -> {
                handleNavigation(event.route)
            }
            is SingleEvent.ShowLoading -> {
                binding.progressBar.visibility = View.VISIBLE
            }
            is SingleEvent.HideLoading -> {
                binding.progressBar.visibility = View.GONE
            }
        }
     }
     
     override fun onPause() {
        super.onPause()
        // 如果不是进入PIP模式，则暂停播放
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && !isInPictureInPictureMode) {
            exoPlayer?.pause()
            // 暂停弹幕
            if (binding.dan.isPrepared && !binding.dan.isPaused) {
                binding.dan.pause()
            }
        }
    }
    
    override fun onResume() {
        super.onResume()
        // 恢复弹幕
        if (binding.dan.isPrepared && binding.dan.isPaused) {
            binding.dan.resume()
        }
        
        // 每次进入页面时增加播放次数
        if (currentVideoId != 0) {
            playCount = SPUtils.getInstance().getInt("play_count_$currentVideoId", 0) + 1
            SPUtils.getInstance().put("play_count_$currentVideoId", playCount)
            updatePlayCountAndTime()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        // 释放播放器资源
        exoPlayer?.release()
        exoPlayer = null
        
        // 释放弹幕资源
        if (binding.dan.isPrepared) {
            binding.dan.release()
        }
    }
    
    // 处理返回键
    @Deprecated("Deprecated in Java")
    override fun onBackPressed() {
        if (isFullscreen) {
            // 如果是全屏状态，切换回普通状态
            toggleFullscreen()
        } else {
            // 如果是普通状态，进入PIP模式并返回首页
            enterPipMode()
            // 返回首页
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                // 使用ARouter导航回首页
                ARouter.getInstance().build("/app/MainActivity").navigation()
            } else {
                super.onBackPressed()
            }
        }
    }

    // 进入PIP模式
    private fun enterPipMode() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // 获取视频播放器的位置信息
            val sourceRectHint = Rect()
            binding.playerView.getGlobalVisibleRect(sourceRectHint)

            // 设置PIP窗口的宽高比，确保宽高不为0
            var width = binding.playerView.width
            var height = binding.playerView.height

            // 如果宽度或高度为0，使用默认值
            if (width <= 0) width = 16
            if (height <= 0) height = 9

            var aspectRatio = Rational(width, height)

            // 检查宽高比是否在允许范围内，如果不在则进行调整
            val ratio = aspectRatio.toFloat()
            if (ratio < 0.418410f) {
                aspectRatio = Rational(41841, 100000) // 使用接近最小值的比例
            } else if (ratio > 2.390000f) {
                aspectRatio = Rational(239, 100) // 使用接近最大值的比例
            }

            // 创建PIP参数
            val pipBuilder = PictureInPictureParams.Builder()
                .setSourceRectHint(sourceRectHint)
                .setAspectRatio(aspectRatio)

            // 进入PIP模式
            enterPictureInPictureMode(pipBuilder.build())
        } else {
            // 对于不支持PIP的设备，正常返回
            super.onBackPressed()
        }
    }


    // 处理PIP模式变化
      override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, newConfig: Configuration) {
         super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig)
         
         if (isInPictureInPictureMode) {
             // 进入PIP模式，隐藏UI控件，只保留视频播放
             binding.btnBack.visibility = View.GONE
             binding.btnShare.visibility = View.GONE
             binding.btnPlayPause.visibility = View.GONE
             binding.timeLayout.visibility = View.GONE
             binding.scrollView.visibility = View.GONE
             // 隐藏弹幕输入框和发送按钮
             binding.dm.visibility = View.GONE
             binding.send.visibility = View.GONE
             // 隐藏弹幕显示
             binding.dan.visibility = View.GONE
             
             // 确保视频继续播放
             exoPlayer?.play()
         } else {
             // 退出PIP模式，恢复UI控件
             binding.btnBack.visibility = View.VISIBLE
             binding.btnShare.visibility = View.VISIBLE
             binding.btnPlayPause.visibility = View.VISIBLE
             binding.timeLayout.visibility = View.VISIBLE
             binding.scrollView.visibility = View.VISIBLE
             // 恢复弹幕输入框和发送按钮
             binding.dm.visibility = View.VISIBLE
             binding.send.visibility = View.VISIBLE
             // 恢复弹幕显示
             binding.dan.visibility = View.VISIBLE
         }
     }
     
     override fun handleNavigation(route: String) {
        // 使用ARouter处理导航
        ARouter.getInstance().build(route).navigation()
     }
     
     // 处理用户离开提示（按Home键）
     override fun onUserLeaveHint() {
        super.onUserLeaveHint()
        // 当用户按下Home键时，进入PIP模式
        if (!isFullscreen && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            enterPipMode()
        }
     }

}



        

